<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="院校名称" prop="colleges_name">
            <el-input
              v-model="queryParams.colleges_name"
              placeholder="请输入院校关键字"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="上传时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">
              <span>新增</span>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="courseList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" sortable="custom" width="75" type="index" />
          <el-table-column label="院校名称" prop="colleges_name" :show-overflow-tooltip="true" />
          <el-table-column label="所在地区" prop="province_text" :show-overflow-tooltip="true" />
          <el-table-column label="所属部门" prop="dept_id_text">
            <template slot-scope="scope">
              <span>{{ scope.row.dept?scope.row.dept.dept_name:"-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上传人" prop="creator" />
          <el-table-column label="创建时间" sortable="custom" prop="createdAt" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" class-name="small-padding fixed-width" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="!multiple && single"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改对话框 -->
        <el-drawer
          ref="drawer"
          :title="title"
          :visible.sync="open"
          direction="rtl"
          custom-class="demo-drawer"
        >
          <div class="demo-drawer__content">
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
              <el-form-item label="院校名称" prop="colleges_name">
                <el-input v-model="form.colleges_name" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="所属省份" prop="province">
                <el-select
                  v-model="form.province"
                  placeholder="请选择地址"
                  style="width: 100%"
                  @change="location1Change"
                >
                  <el-option
                    v-for="item in location1"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="所属城市" prop="city">
                <el-select
                  v-model="form.city"
                  filterable
                  placeholder="请选择地址"
                  style="width: 100%"
                  @change="location2Change"
                >
                  <el-option
                    v-for="item in location2"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="所属片区" prop="area">
                <el-select
                  v-model="form.area"
                  filterable
                  placeholder="请选择地址"
                  style="width: 100%"
                  @change="location3Change"
                >
                  <el-option
                    v-for="item in location3"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="院校所属部门" prop="dept_id">
                <treeselect
                  v-model="form.dept_id"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  placeholder="请选择归属部门"
                  @input="handleChange"
                />
              </el-form-item>
              <el-form-item label="所属教学点" prop="teaching_point_id">
                <el-select
                  v-model="form.teaching_point_id"
                  remote
                  filterable
                  placeholder="请选择教学点"
                  :remote-method="remoteSchool"
                  :loading="selectload"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in schoolList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-drawer>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import {
  getAcademyList,
  addAcademy,
  editAcademy,
  delAcademy
} from '@/api/admin/sys-academy'
import { getRegion } from '@/api/admin/sys-course'
import { treeselect } from '@/api/admin/sys-dept'
import { getSchoolList } from '@/api/admin/sys-academy'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { flatten } from '@/utils/index'

export default {
  name: 'SysAcademy',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      chooseIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      courseList: [],
      // 排序字段
      order: 'createdAtOrder',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        created_at: undefined,
        colleges_name: undefined
      },
      form: {},
      rules: {
        colleges_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择所属省份', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选择所属城市', trigger: 'blur' }],
        area: [{ required: true, message: '请选择所属片区', trigger: 'blur' }],
        dept_id: [
          { required: true, message: '请选择院校所属部门', trigger: 'blur' }
        ],
        teaching_point_id: [
          { required: true, message: '请选择所属教学点', trigger: 'blur' }
        ]
      },
      location1: null,
      location2: null,
      location3: null,
      selectload: false,
      deptOptions: [],
      schoolParams: {
        pageIndex: 1,
        pageSize: 1000,
        name: undefined
      },
      schoolList: []
    }
  },
  watch: {
    open(newVal) {
      if (newVal === true && this.form.province) {
        getRegion({ parent_id: this.form.province }).then(res => {
          this.location2 = res.data
        })
        if (this.form.city) {
          getRegion({ parent_id: this.form.city }).then(res => {
            this.location3 = res.data
          })
        }
      }
    }
  },
  created() {
    this.getList()
    this.host = process.env.VUE_APP_BASE_API
    this.getLocation()
    treeselect().then(response => {
      this.deptOptions = response?.data
    })
    this.getSchoolList()
  },
  methods: {
    getSchoolList() {
      getSchoolList(this.schoolParams).then(res => {
        this.schoolList = res?.data?.list || []
        this.selectload = false
      })
    },
    /** 获取所属大区 */
    getLocation() {
      getRegion({ parent_id: 1 }).then(res => {
        this.location1 = res?.data
      })
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true
      getAcademyList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.courseList = response.data.list
          this.total = response.data.count
          this.loading = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseIds = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.chooseIds
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delAcademy({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加院校'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = JSON.parse(JSON.stringify(row))
      this.open = true
      this.title = '修改院校'
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id) {
            // const payload = {
            //   id: this.form.id,
            //   colleges_name: this.form.colleges_name,
            //   province: this.form.province,
            //   province_text: this.form.province_text,
            //   city: this.form.city,
            //   city_text: this.form.city_text,
            //   dept_id: this.form.dept_id
            // };
            editAcademy(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess(res.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(res.msg)
              }
            })
            return
          }
          addAcademy(this.form).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.open = false
              this.getList()
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    location1Change(value) {
      const provinceText = this.location1?.find(item => item.id === value)
      this.form = {
        ...this.form,
        province_text: provinceText?.name,
        city: null,
        city_text: '',
        area: null
      }
      getRegion({ parent_id: value }).then(res => {
        this.location2 = res.data
      })
    },
    location2Change(value) {
      const cityText = this.location2?.find(item => item.id === value)
      this.form = {
        ...this.form,
        city_text: cityText?.name,
        area: null
      }
      getRegion({ parent_id: value }).then(res => {
        this.location3 = res.data
      })
    },
    location3Change(value) {
      const areaText = this.location3?.find(item => item.id === value)
      this.form = {
        ...this.form,
        area_text: areaText?.name
      }
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    handleChange(value) {
      const filtrate = flatten(this.deptOptions)?.filter(
        item => item?.id === value
      )
      this.form = {
        ...this.form,
        dept_id_text: filtrate[0]?.label
      }
    },

    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        this.selectload = false
      } else {
        this.location1 = []
      }
    },
    remoteSchool(data) {
      if (data !== '') {
        this.selectload = true
        this.schoolParams.name = data
        this.getSchoolList()
      } else {
        this.schoolList = []
      }
    }
  }
}
</script>
